// 用户模块   // 验证登陆状态

const router =  require('express').Router()
const query = require('../mysql/index')
const timeFormat = require("../utils/timeFormat")


router.get("/",async (req,res)=>{
   
    res.render("admin/user")
})

router.get("/users/:id",async(req,res)=>{

    let data = await query("select id,username,msg,create_time,status from user_table where id=?",[req.params.id]);
    if(data.length > 0){
        res.render('userinfo',{
            data:{
                ...data[0],
                create_time:timeFormat(data[0].create_time)
            }
        })
    }else{
        res.json({
            code:400
        })
    }
})

router.get("/getAll",async (req,res)=>{
    let data = await query("select * from user_table");
    res.json({
        code:0,
        data
    })
})


// 修改用户状态
router.post("/editStatus",async (req,res)=>{
    let data = await query("UPDATE `user_table` SET `status`=? WHERE (`id`=?)",[req.body.status,req.body.id]);
    res.json({
        code:data.affectedRows>0?0:400,
        msg:data.affectedRows>0?'success':'error'
    })
})



router.post("/edit",async(req,res)=>{
    // 查询原有名字
    let oldName = await query('select * from user_table where id = ?',[req.body.id]);
    // 查询是否重复
    let isRepeat = await query(`select * from user_table where username = ? and username != ?`,[req.body.username,oldName[0].username])

    if(isRepeat.length == 0){
        let sql = "UPDATE `user_table` SET `username`=?,password=?, `msg`=? WHERE (`id`= ?)";
        await query(sql,[req.body.username,req.body.password,req.body.msg,req.body.id]);
        res.json({
            code:200,
            msg:'success'
        })
    }else{
        res.json({
            code:400,
            msg:'该用户名已存在，请更换！'
        })
    }
 

})

/**
 * 登录页
 */
router.get("/userLogin",(req,res)=>{
    res.render('userLogin.ejs')
})


/**
 * 登录
 */
router.post("/doUserLogin",async(req,res)=>{
    let data = await query("select id,username,msg,create_time,status from user_table where username=? and password=?",[req.body.username,req.body.password]);
    if(data.length > 0){
        req.session.user=data[0]
        res.json({
            code:0,
            msg:'登陆成功',
            info:data[0]
        })
    }else{
        res.json({
            code:400,
            msg:'登陆失败，请检查用户名或密码',
        })
    }
})


//退出登录
router.get("/logout",(req,res)=>{
    req.session.user = null;
    res.json({code:0})
})

/**
 * 注册
 */
 router.get("/regrister",(req,res)=>{
    res.render('regrister.ejs')
})
/**
 * 修改个人信息
 */
module.exports = router;